<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

/**
* This controller is used for JAEmail feature of the component
*/
class JAJobBoardControllerJAImportUsers extends JAJobBoardController {
/**
     * Constructor
     */
    function __construct( $location = array() )
    {
    	
        parent::__construct( $location );        
        // Register Extra tasks
        $this->registerTask( 'add',     'edit' );
        $this->registerTask( 'drop',     'remove' );
        $this->registerTask( 'apply',   'save' );        
		$this->registerTask( 'non-approved', 	'approved');
		JRequest::setVar('table_name', 	'ja_jobs');
    }
    
    /**
    * Display current jajobs of the component to administrator
    * 
    */
    function display(){
    	$temp = $this->getModel('jaconfiguration');
    	$jbconfig = $temp->getItems();
		$jbconfig = new JParameter($jbconfig->data);
		JRequest::setVar('config', $jbconfig);  
		
    	switch($this->getTask())
		{
			case 'add'     :
			{
				JRequest::setVar( 'hidemainmenu', 1 );
				JRequest::setVar( 'edit', false );
				JRequest::setVar( 'layout', 'form' );
				// Checkout the jaconfig
				$model = $this->getModel('jajobs');
				$model->checkout();
			} break;
			case 'edit':
			{
				JRequest::setVar( 'hidemainmenu', 1 );
				JRequest::setVar( 'edit', true );
				JRequest::setVar( 'layout', 'form' );
				// Checkout the jaconfig
				$model = $this->getModel('jajobs');
				$model->checkout();
			} break;
		}
	
		parent::display();
    }
    
    /**
    * Import as JobSeeker user
    * 
    */
    function import_jobseeker(){
    	$this->import_users("Job Seeker User");
    }
    
    /**
    * Import as Employer user
    * 
    */
    function import_employer(){
    	$this->import_users("Employer User");
    }
    
    function import_users($userType){
        global $option, $jbconfig;
    	$db =& JFactory::getDBO();
    	$msg = "";
    	
    	$cid = JRequest::getVar("cid", "");
    	if( is_array($cid) ){
    	    $i=0;
    	    foreach ( $cid as $user_id ){
    	        // Update user params
    	        $user = JFactory::getUser($user_id);
    	        $user->setParam('usertype', $userType);
    	        $user->save();
    	        
    	        if( $userType == "Job Seeker User" )
    	        	$query = "INSERT INTO #__ja_resumes(user_id, approved) VALUES ('{$user_id}', '1')";
    	        else{
					$query = "INSERT INTO #__ja_profiles(user_id, approved) VALUES ('{$user_id}', '1')";
					$db->setQuery("INSERT INTO #__ja_employers(user_id) VALUES ('{$user_id}')");
					$db->query();
				}
    	        $db->setQuery($query);
    	        $db->query();
    	        $i++;
    	    }
    	    $msg = JText::_("Successfully imported {$i} user(s)");
    	}
    	
        $this->setRedirect("index.php?option=$option&view=jaimportusers", $msg);
    }
    
    /**
    * Cancel current operation
    * 
    */
    function cancel(){
    	global $option;
        $this->setRedirect("index.php?option=$option&view=jajobs");
    }
    
    /**
    * Remove a jajobs row
    * 
    */   
    function remove(){
    	global $option;
 
    	// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
        
		$cid = JRequest::getVar('cid',array(), 'post', 'array');
		$msg = '';
		$allow_del = true;
		foreach ($cid as $id)
		{
			$applist = getItemByFieldName('ja_applications','job_id',$id);
			if (count($applist)>=1)
			{
				$allow_del = false;
				$job = getItemByFieldName('ja_jobs','id',$id);
				$job = $job[0];
				JError::raiseWarning(1,  JText::_("You can not delete")." '$job->title' job. ".JText::_("Please delete all application of")." '$job->title'<br />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp ");
				return $this->setRedirect("index.php?option=$option&view=jajobs");
			}
		}
		if (!$allow_del)
		{
			$this->setRedirect("index.php?option=$option&view=jajobs");
		}
		
        $model =& $this->getModel('jajobs');
        if(($n = $model->remove()) < 0){
             JError::raiseWarning( 500, $row->getError() );
		}
		if ($n==1)
			$this->setMessage(JText::_('Successfully removed item!'));
		else 
			$this->setMessage(JText::_('Successfully removed items!'));
		$this->setRedirect("index.php?option=$option&view=jajobs");
	}
	
	
	/**
	* Save categories record
	*/
	function save(){
		
		global $option;
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		$cache = & JFactory::getCache($option);
		$cache->clean();

		$model	=& $this->getModel('jajobs');
//		$post	= JRequest::get('post');
		$post    = JRequest::get('request');
		$user = JFactory::getUser($post['user_id']);
		if(!$post['user_id'] || !$user->id){
			JError::raiseWarning(1, JText::_('Please choose Employer!'));
			JRequest::setVar('task', 'edit');
			JRequest::setVar('layout', 'form');
			JRequest::setVar('view', 'jajobs');
			parent::display();
			return;
		}
		
		foreach ($post as $k=>$row){
			if(is_array($row) && $k!='cid'){
				$post[$k] = implode(',', $row);
			}
		}
		
		
		$model->setState( 'request', $post );
		$msg = '';
		
		if ($id = $model->store()) {
			
			if ((isset($cid[0]))&&$cid[0]!=0)
				$msg = JText::_( 'Successfully updated job' );
			else 
				$msg = JText::_( 'Successfully created job' );
			switch ( $this->_task ) {
			case 'apply':
				$this->setRedirect( "index.php?option=$option&view=jajobs&task=edit&cid[]=$id" , $msg );
				break;

			case 'save':
			default:
				$this->setRedirect( "index.php?option=$option&view=jajobs", $msg );
				break;
		}
		} else {
			$id = JRequest::getVar('cid');
			JRequest::setVar('postback',true);
//			$msg = JText::_('Error found!Fail to save job item');
//			JError::raiseWarning(403, $msg);
			
			JRequest::setVar('layout','form');
			JRequest::setVar('task','edit');
			JRequest::setVar('cid[]',$id);
			
			parent::display();
//			$this->setRedirect( "index.php?option=$option&view=jajobs&task=edit&cid[]=$id" , $msg );
		}
		
		
	}	
	
	/**
	* Approved job
	*/
	/**
	 * Approved list item 
	 * @return void
	 **/
	function approved(){
		global  $option;
		
		if($this->getTask()=='approved')
		{ 
			$status = 'Approved';
			$succ_msg = JText::_('Successfully approved job item(s)!');
		}
		else 
		{
			$status = 'Non-Approved';
			$succ_msg = JText::_('Successfully disapproved job item(s)!');
		}
		
		$model = $this->getModel('jajobs');
				
		if (!$model->approved($status)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
			exit();
		}
		//$cache = & JFactory::getCache('jajobs');
		//$cache->clean();	
		
		$this->setRedirect("index.php?option=$option&view=jajobs", $succ_msg);
	}	
	
     /**
    * Edit list column in table list
    * 
    */
    function editList(){
    	$this->setRedirect('index.php?option=com_jajobboard&view=jafieldlist&filter_table=ja_jobs'); 	
    }
	
    /**
    * Move down the order of field list item
    * 
    */
    function orderdown(){
    	global $option;
        // Check for request forgeries
        JRequest::checkToken() or jexit( 'Invalid Token' );
        
        $cid    = JRequest::getVar( 'cid', array(), 'post', 'array' );
        JArrayHelper::toInteger($cid);
        
        $task = JRequest::getVar('task', 'orderdown');

        if (isset($cid[0]) && $cid[0]) {
            $id = $cid[0];
        } else {
            $this->setRedirect( "index.php?option=$option&view=jajobs", JText::_('No Items Selected') );
            return false;
        }

        $model =& $this->getModel( 'jajobs' );
        $movement = $task == 'orderdown' ? 1 : -1;

        if($model->orderItem($id, $movement)){
            $msg = $movement > 0 ? JText::_( 'Item Moved Down' ) : JText::_( 'Item Moved Up' );
        }
        
        $this->setRedirect( "index.php?option=$option&view=jajobs", $msg );
    }
    
    /**
    * Save the item(s) order
    */
    function saveorder()
    {
    	global $option;
        // Check for request forgeries
        JRequest::checkToken() or jexit( 'Invalid Token' );
        
        $cid    = JRequest::getVar( 'cid', array(), 'post', 'array' );
        JArrayHelper::toInteger($cid);

        $model =& $this->getModel( 'jajobs' );
		$msg = '';
        if ($model->setOrderchu($cid)) {
            $msg = JText::_( 'New ordering saved' );
        } else {            
			JError::raiseWarning(1,  $model->getError());
        }
        $this->setRedirect(  "index.php?option=$option&view=jajobs", $msg );
    }
    
    function remove_attach()
    {
    	$model    =& $this->getModel( 'jajobs' );
    	$model->remove_attach();
         exit;
    }
    
    function download(){
         $model    =& $this->getModel( 'jajobs' );    
         $model->download();
         exit;
    }
    
}